package com.example.demo.config;

import com.example.demo.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author shenb
 * @date 2022-06-28 14:31
 */
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class MyCustomErrorController extends AbstractErrorController {

    private static final Logger logger = LoggerFactory.getLogger(MyCustomErrorController.class);

    private final ErrorAttributes errorAttributes;

    @Autowired
    public MyCustomErrorController(ErrorAttributes errorAttributes, List<ErrorViewResolver> errorViewResolvers) {
        super(errorAttributes, errorViewResolvers);
        this.errorAttributes = errorAttributes;
    }

    private ErrorAttributeOptions getErrorAttributeOptions(HttpServletRequest request, MediaType all) {
        return ErrorAttributeOptions.of(
                ErrorAttributeOptions.Include.MESSAGE,
                ErrorAttributeOptions.Include.EXCEPTION);
    }

    @RequestMapping
    public ResponseEntity<Result<Void>> error(Model model, HttpServletRequest request, HttpServletResponse response) {
        HttpStatus status = getStatus(request);
        if (status == HttpStatus.NO_CONTENT) {
            return new ResponseEntity<>(status);
        }
        WebRequest webRequest = new ServletWebRequest(request);
        Throwable exception = this.errorAttributes.getError(webRequest);
        if (exception instanceof ConstraintViolationException) {
            status = HttpStatus.BAD_REQUEST;
        }

        Map<String, Object> attrs = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
        String path = (String) attrs.get("path");
        String errorInfo = (String) attrs.get("error");
        switch (status) {
            case INTERNAL_SERVER_ERROR: {
                String exceptionClzName = (String) attrs.get("exception");
                Result<Void> result = Result.failure((String) attrs.getOrDefault("message", errorInfo), null);
                return new ResponseEntity<>(result, status);
            }

            default: {
                String fmtMsg = errorInfo;
                if (exception != null) {
                    if (exception instanceof BindingResult) {
                        fmtMsg = prettyBindingResult((BindingResult) exception);
                    } else {
                        fmtMsg = exception.getMessage();
                    }
                }
                logger.warn("Request[{}] failed with status[{}], msg: {}", path, status.value(), fmtMsg);

                Result<Void> result = Result.failure(fmtMsg, null);
                return new ResponseEntity<>(result, status);
            }
        }
    }

    private String prettyBindingResult(BindingResult result) {
        Map<String, Set<String>> errorDetails = result.getAllErrors().stream().collect(Collectors.groupingBy(it -> ((FieldError) it).getField(), Collectors.mapping(ObjectError::getDefaultMessage, Collectors.toSet())));
        StringBuilder sb = new StringBuilder("Validation failed for object='").append(result.getObjectName()).append("', details: ");
        errorDetails.forEach((key, value) -> {
            sb.append(key).append(": ").append(String.join(", ", value)).append("; ");
        });
        sb.delete(sb.length() - 2, sb.length());
        return sb.toString();
    }

    @ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
    public ResponseEntity<String> mediaTypeNotAcceptable(HttpServletRequest request, Exception e) {
        logger.error("Global exception catch: mediaTypeNotAcceptable", e);

        HttpStatus status = getStatus(request);
        return ResponseEntity.status(status).build();
    }
}